package net.xdclass.controller;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.domain.Video;
import net.xdclass.service.VideoService;
import org.apache.ibatis.annotations.Results;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/api/v1/video_order")
@Slf4j
public class OrderController {

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;
    @Resource
    private VideoService videoService;
    @RequestMapping("/find_by_id")
    public Video find_by_id(Integer videoId){
        List<ServiceInstance> instances = discoveryClient.getInstances("xdclass-video-service");
        ServiceInstance serviceInstance = instances.get(0);
        String domain = serviceInstance.getHost() + ":" + serviceInstance.getPort();
//        String url = "http://"+domain+"/api/v1/video/find_by_id?id=30";
//        String url = "http://xdclass-video-service/api/v1/video/find_by_id?id=30";
//        log.info("保存订单 调用视频服务 url={}", url);
//        Video byId = restTemplate.getForObject(url, Video.class);
        Video byId = videoService.findById(30);
        byId.setCreateTime(new Date());
        byId.setTitle("restTemplate测试");
        System.out.println(JSON.toJSONString(byId));
        return byId;
    }

    @RequestMapping("/save")
    public Video save(){
        Video video = new Video();
        video.setId(20);
        Video save = videoService.save(video);
        save.setCreateTime(new Date());
        save.setTitle("restTemplate测试");
        System.out.println(JSON.toJSONString(save));
        return save;
    }

    @RequestMapping("/list")
    public Video list(){
//        int i = 1 / 0;
//        try {
//            TimeUnit.SECONDS.sleep(3);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        Video video = new Video();
        video.setId(20);
        Video save = videoService.save(video);
        save.setCreateTime(new Date());
        save.setTitle("restTemplate测试");
        System.out.println(JSON.toJSONString(save));
        return save;
    }

    @Resource
    private HttpServletRequest request;
    @RequestMapping("/orderlist")
    public String orderlist(){
        String result = "orderlist:" + request.getServerPort();
        log.info(result);
        return "orderlist:" + request.getServerPort();
    }
}
